<template>
  <div class="lg:p-8">
    <div class="mx-auto  flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
      <div class="flex flex-col space-y-2 text-center">
        <h1 class="text-2xl font-semibold tracking-tight">
          Login an account
        </h1>
        <p class="text-sm text-muted-foreground">
          通过账号密码快速登录
        </p>
      </div>
      <form >
        <div class="grid gap-2">
          <div class="grid gap-2">
            <Label class="font-bold" for="username">用户名</Label>
            <Input
                class="ring-1 ring-discord-100"
                id="username"
                placeholder="请输入用户名"
                type="username"
                auto-capitalize="none"
                auto-complete="email"
                auto-correct="off"
                v-model="User.username"
            />
            <Label class="font-bold" for="password">密码</Label>
            <Input
                class="ring-1 ring-discord-100"
                id="password"
                placeholder="请输入用户密码"
                type="password"
                auto-capitalize="none"
                auto-complete="email"
                auto-correct="off"

                v-model="User.password"
            />
          </div>
          <Button type="button" @click="login" class=" hover:bg-blue-400 bg-blue-500">
            登录
          </Button>
        </div>
      </form>
      <el-alert
          v-if="flag"
          title="账号信息填写有误"
          type="error"
          description="请检查"
          show-icon
      />
      <p class="">
       还没账户？
        <router-link class="text-blue-600" to="/reg">
          快速注册
        </router-link>
      </p>

    </div>
  </div>
</template>
<script setup lang="ts">

import UserAuthForm from "@/components/UserAuthForm.vue";
import {Button} from "@/components/ui/button";
import {Label} from "@/components/ui/label";
import {Input} from "@/components/ui/input";
import { ref,reactive } from 'vue'
import axios from "axios";
import router from "@/router.ts";

const User = reactive({
  username:'',
  password:'',

})

let flag = ref(false)

function login(){
  flag.value = false;
  if(isNull()){
    axios.post('http://localhost:8080/users/login', User)
        .then(response => {
        if(response.data.data.isLogin){
          console.log(response)
          // 保存 SA-Token 到 LocalStorage
          localStorage.setItem('sa-token', response.headers['sa-token']);
          localStorage.setItem('user', JSON.stringify(response.data.user));
          router.push("/index")
        }else {
          alert('账号密码错误');
        }
        })
        .catch(error => {
          alert('登陆失败');
        });
  }else {
    flag.value = true;
    console.log(flag)
  }
}
function isNull(){
  if(User.username == '' || User.password == ''){
    return false
  }else {
    return true
  }
}
</script>
